import type { RequestInstanceState } from './type';
import { addToast } from "@heroui/react";
import { debounce } from 'lodash';

export function showErrorMsg(state: RequestInstanceState, message: string) {
  if (!state.errMsgStack?.length) {
    state.errMsgStack = [];
  }

  const isExist = state.errMsgStack.includes(message);

  if (!isExist) {
    state.errMsgStack.push(message);

    // 使用防抖，300ms 内的相同消息只显示一次
    const debouncedAddToast = debounce((msg: string) => {
      addToast({ title: msg });
    }, 300);

    debouncedAddToast(message);

    // 2秒后从错误栈中移除该消息
    setTimeout(() => {
      const index = state.errMsgStack.indexOf(message);
      if (index > -1) {
        state.errMsgStack.splice(index, 1);
      }
    }, 2000);
  }
}
